package com.rxh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rxh.mapper.merchant.MerchantQuestionMapper;
import com.rxh.mapper.sys.SysAreaMapper;
import com.rxh.mapper.sys.SysLogMapper;
import com.rxh.pojo.base.Page;
import com.rxh.pojo.base.PageResult;
import com.rxh.pojo.merchant.MerchantQuestionWithBLOBs;
import com.rxh.pojo.sys.SysArea;
import com.rxh.pojo.sys.SysLog;
import com.rxh.service.ConstantService;
import com.rxh.service.MerchantService;
import com.rxh.service.SystemService;
import com.rxh.utils.DateUtils;
import com.rxh.utils.SystemConstant;
import com.rxh.utils.UUID;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: 陈俊雄
 * Date: 2018/5/3
 * Time: 17:24
 * Project: Management
 * Package: com.rxh.service.impl
 */
@Service
public class SystemServiceImpl implements SystemService {
    @Resource
    private SysLogMapper sysLogMapper;

    @Resource
    private SysAreaMapper areaMapper;

    @Resource
    private MerchantService merchantService;

    @Resource
    private ConstantService constantService;

    @Resource
    private MerchantQuestionMapper merchantQuestionMapper;

    @Override
    public void saveSystemLog(SysLog log) {
        log.setId(UUID.createKey("sys_log"));
        sysLogMapper.insertSelective(log);
    }

    @Override
    public PageResult getSystemLog(Page page) {
        // 设置分页信息
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (page.getOrderBy() == null || page.getOrderBy().size() == 0) {
            PageHelper.orderBy("id DESC");
        } else {
            page.getOrderBy().forEach((key, value) -> PageHelper.orderBy(key + " " + value));
        }
        if (page.getLogSearch() != null && page.getLogSearch().getEndTime() != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(page.getLogSearch().getEndTime());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            page.getLogSearch().setEndTime(calendar.getTime());
        }
        List<SysLog> logs = sysLogMapper.selectBySearchInfo(page.getLogSearch());
        PageInfo<SysLog> pageInfo = new PageInfo<>(logs);
        // 获取查询结果
        PageResult result = new PageResult();
        result.setRows(logs);
        result.setTotal(pageInfo.getTotal());
        result.setAllPage(pageInfo.getPages());
        return result;
    }

    @Override
    public List<SysArea> getAreaInfoByCountryCode(String countryCode) {
        // 获取对应国家编码的所有地镇信息
        List<SysArea> areas = areaMapper.selectAreaByCountryCode(countryCode);
        // 获取省List对象
        List<SysArea> firstLevelAreaList = areas
                .stream()
                .filter(sysArea -> sysArea.getLevel() == 0)
                .collect(Collectors.toList());
        // 获取市List对象
        List<SysArea> secondLevelAreaList = areas
                .stream()
                .filter(sysArea -> sysArea.getLevel() == 1)
                .collect(Collectors.toList());
        // 获取县List对象
        List<SysArea> thirdLevelAreaList = areas
                .stream()
                .filter(sysArea -> sysArea.getLevel() == 2)
                .collect(Collectors.toList());
        // 获取镇List对象
        List<SysArea> fourthLevelAreaList = areas
                .stream()
                .filter(sysArea -> sysArea.getLevel() == 3)
                .collect(Collectors.toList());
        // 获取市Map对象（以父级ID为Key，Value为List）
        Map<Integer, List<SysArea>> secondAreaListMap = secondLevelAreaList
                .stream()
                .collect(Collectors.groupingBy(SysArea::getPid));
        // 获取县Map对象（以父级ID为Key，Value为List）
        Map<Integer, List<SysArea>> thirdAreaListMap = thirdLevelAreaList
                .stream()
                .collect(Collectors.groupingBy(SysArea::getPid));
        // 获取镇Map对象（以父级ID为Key，Value为List）
        Map<Integer, List<SysArea>> fourthAreaListMap = fourthLevelAreaList
                .stream()
                .collect(Collectors.groupingBy(SysArea::getPid));
        // 循环县，根据ID从镇Map对象获取对应List
        thirdLevelAreaList.forEach(sysArea -> sysArea.setChildArea(fourthAreaListMap.get(sysArea.getId())));
        // 循环市，根据ID从县Map对象获取对应List
        secondLevelAreaList.forEach(sysArea -> sysArea.setChildArea(thirdAreaListMap.get(sysArea.getId())));
        // 循环省，根据ID从市/镇Map对象获取对应List
        firstLevelAreaList.forEach(sysArea -> {
            sysArea.setChildArea(secondAreaListMap.get(sysArea.getId()));
            if (sysArea.getChildArea() == null) {
                sysArea.setChildArea(thirdAreaListMap.get(sysArea.getId()));
            }
        });
        // 循环
        return firstLevelAreaList;
    }

    @Override
    public Map<String, Object> getMerchantOpinionInit(Integer merchantId) {
        Map<String, Object> init = new HashMap<>();
        init.put("questionType", constantService.getConstantByGroupName(SystemConstant.QUESTION_TYPE));
        init.put("questionStatus", constantService.getConstantByGroupName(SystemConstant.QUESTION_STATUS));
        return init;
    }

    @Override
    public PageResult getMerchantQuestionBySearchInfo(Page page) {
        // 设置分页信息
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (page.getOrderBy() == null || page.getOrderBy().size() == 0) {
            PageHelper.orderBy("time DESC");
        } else {
            page.getOrderBy().forEach((key, value) -> PageHelper.orderBy(key + " " + value));
        }
        // 执行查询
        if (page.getSearchInfo() != null && page.getSearchInfo().getEndDate() != null) {
            page.getSearchInfo().setEndDate(DateUtils.setEndDate(page.getSearchInfo().getEndDate()));
        }
        List<MerchantQuestionWithBLOBs> list = merchantQuestionMapper.selectBySearchInfo(page.getSearchInfo());
        PageInfo<MerchantQuestionWithBLOBs> pageInfo = new PageInfo<>(list);
        // 获取查询结果
        PageResult result = new PageResult();
        result.setRows(list);
        result.setTotal(pageInfo.getTotal());
        result.setAllPage(pageInfo.getPages());
        // 返回结果
        return result;
    }

    @Override
    public Boolean addMerchantQuestion(MerchantQuestionWithBLOBs merchantQuestionWithBLOBs, Integer merchantId) {
        merchantQuestionWithBLOBs.setId(UUID.createKey("merchant_question", "MQ"));
        merchantQuestionWithBLOBs.setMerId(merchantId);
        merchantQuestionWithBLOBs.setTime(new Date());
        merchantQuestionWithBLOBs.setStatus(SystemConstant.MERCHANT_QUESTION_STATUS_PENDING);
        return merchantQuestionMapper.insertSelective(merchantQuestionWithBLOBs) == 1;
    }

    @Override
    public Boolean updateMerchantQuestion(MerchantQuestionWithBLOBs merchantQuestionWithBLOBs) {
        return merchantQuestionMapper.updateByPrimaryKeyWithBLOBs(merchantQuestionWithBLOBs) == 1;
    }
}